package com.example.seleniumautotest.controller;

/*
* 在项目初始化后，立即执行
* 该类为selenium项目的全局配置类
* */

import com.example.seleniumautotest.utils.DelayUtils;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Objects;

@Component
@Slf4j
public class OverallConfigInit {

    @Autowired
    private DelayUtils delayUtils;
    @Autowired
    private Environment environment;

    public void overallLoad(ChromeDriver chromeDriver,String homePath){
        // 打开首页
        chromeDriver.get(homePath);
        // 窗口最大化
        chromeDriver.manage().window().maximize();

        // 添加cookie
        HashMap<String, String> map = cookieDecide();
        for (String key:map.keySet()) {
            log.info("cookie信息：{} : {}",key,map.get(key));
            chromeDriver.manage().addCookie(new Cookie(key,map.get(key)));
        }
        // 刷新
        chromeDriver.navigate().refresh();
        // 等待页面加载完成
        log.info("正在等待首页数据加载……");
        delayUtils.delay(8);
    }

    private HashMap<String, String> cookieDecide(){
        String property = environment.getProperty("configCookie.cookieArray");
        HashMap<String, String> map = new HashMap<>();

        if (Objects.nonNull(property) && !property.equals("")){
            String[] split = property.split(",");
            for (String tmp:split
                 ) {
                map.put(tmp,environment.getProperty("configCookie." + tmp));
            }
        }

        return map;
    }
}
